#include "head.h"
/* Usage: */
#include "timeout.h"

int addSocket(const int socket_fd, timeout_t *timeout)
{
    timeout->flag = 0;
    timing_t *new_node = (timing_t *)malloc(sizeof(timing_t));
    if(new_node == NULL)
    {
        //LOG(ERROR, "Memory allocation failed");
        return -1; 
    }
    new_node->socket_fd = socket_fd;
    new_node->next = timeout->head;
    timeout->head = new_node;
    return 0;
}

int deleteSocket(const int socket_fd, timeout_t *timeout)
{
    if(timeout->head == NULL)
    {
        //LOG(ERROR, "List does not exist");
        return -1;
    }
    timing_t *cur_node = timeout->head;
    timing_t *pre_node = NULL;
    while(cur_node != NULL)
    {
        if(cur_node->socket_fd == socket_fd)
        {
            if(pre_node == NULL)
            {
                timeout->head = cur_node->next;
            }
            else
            {
                pre_node->next = cur_node->next;
            }
            free(cur_node);
            return 0;
        }
        pre_node = cur_node;
        cur_node = cur_node->next;
    }
    //LOG(ERROR, "Socket not found");
    return -1;
}

int timeoutCheck(int socket_fd, int epoll_fd, int idx_fds[], timeout_t *timeout)
{
    //根据当前时间获得存储位置
    int idx = time(NULL) % 30;
    int pre_idx = (idx + 29) % 30;

    timeout[pre_idx].flag = 1;
    if(timeout[idx].flag == 1 && timeout[idx].head != NULL)
    {
        timing_t *cur_node = timeout[idx].head;
        while(cur_node != NULL)
        {
            int tmp_fd = cur_node->socket_fd;
            timing_t *tmp_node = cur_node;
            cur_node = cur_node->next;

            if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, tmp_fd, NULL) == -1)
            {
                //LOG(ERROR, "Failed to remove socket from epoll");
            }

            if(close(tmp_fd) == -1)
            {
                //LOG(ERROR, "Failed to close socket");
            }

            free(tmp_node);
        }
        timeout[idx].head = NULL;
    }

    timeout[idx].flag = 0;
    int old_idx = idx_fds[socket_fd];
    if(old_idx != -1)
    {
        deleteSocket(socket_fd, &timeout[old_idx]);
    }
    idx_fds[socket_fd] = idx;
    return addSocket(socket_fd, &timeout[idx]);
}
